<?php
namespace Framework\Http;

/**
 *  //基础
 *	$session->open();
 *	$session->close();
 *	$session->destroy();//销毁session
 *  
 *  //增删改查
 *	$session->all();
 *	$session->get('name');
 *	$session->set('name', '');
 *	$session->remove('name');
 *	$session->flush();//清空session
 *	
 *  //值判断
 *	$session->has('name');
 *	$session->exists('name');
 *  
 *  //遍历所有session变量
 *  foreach ($session->all() as $name => $value)
 *
 *  
 */
class Seesion
{
	public function __construct(){
		$path = app('config')->get('session.files');
		if( is_dir($path) ){
			session_save_path($path);
		}else{
			throw new \Exception("Session保存路径不是有效目录 {$path}");
		}

		//开启
		$this->open();


		// echo session_save_path();
	}

    public function __get(string $name)
    {
        $getter = 'get' . ucfirst($name);
        if (method_exists($this, $getter)) {
            return $this->$getter();
        }

		throw new \Exception('获取未知属性 : ' . get_class($this) . '::' . $name);
    }

    public function getId()
    {
        return session_id();
    }

    /**
     * @return bool 会话是否已经开始
     */
    public function getIsActive() : bool
    {
        return session_status() === PHP_SESSION_ACTIVE;
    }

	public function open()
	{
        if ( !$this->getIsActive() ){
            app('config')->get('debug') ? session_start() : @session_start();
        }
	}


	public function close()
	{
		if ( $this->getIsActive() ){
			app('config')->get('debug') ? session_write_close() : @session_write_close();
        }
	}


	//销毁session中所有已注册的数据
	public function destroy($value='')
	{
		if ($this->getIsActive()){
            session_unset();
            session_destroy();
		}
	}

	//获取Session
	public function get($key, $default=null)
	{
		$this->open();
		return $this->exists($key) ? $_SESSION[$key] : $default ;
	}

	//设置Session
    public function set($key, $value)
    {
        $this->open();
        $_SESSION[$key] = $value;
    }

    //删除Session
    public function remove($key)
    {
        $this->open();
        if (isset($_SESSION[$key])) {
            $value = $_SESSION[$key];
            unset($_SESSION[$key]);

            return $value;
        }

        return null;
    }

	//获取所有 Session 数据
	public function all()
	{
		$this->open();
		return $_SESSION;
	}

	//判断 Session 中是否存在某个值  (该值存在且不为null)
	public function has($key)
	{
        $this->open();
		return isset($_SESSION[$key]) && $_SESSION[$key]!==null ;
	}

	//判断 Session 中是否存在某个值 (该值存在即使null)
	public function exists($key)
	{
        $this->open();
		return isset($_SESSION[$key]);
	}


	//闪存数据
	public function flash($key, $value)
	{
		# code...
	}

	//重新生成 Session ID
	public function regenerate()
	{
		# code...
	}


	//删除所有session
	public function flush()
	{
        $this->open();
        foreach (array_keys($_SESSION) as $key) {
            unset($_SESSION[$key]);
        }
	}
}